package easy.最长公共前缀;

/**
 * @author CodeX
 * @since 2021-09-24 10:35:59
 */
public class LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {

        if (strs == null || strs.length == 0) {
            return "";
        }

        int minLength = Integer.MAX_VALUE;
        for (String str : strs) {
            minLength = Math.min(minLength, str.length());
        }

        int start = 0, end = minLength;
        while (start < end) {
            int mid = (end - start + 1) / 2 + start;
            if (isCommonPrefix(strs, mid)) {
                start = mid;
            } else {
                end = mid - 1;
            }
        }

        return strs[0].substring(0, start);
    }

    public static boolean isCommonPrefix(String[] strs, int length) {
        String str0 = strs[0].substring(0, length);
        for (int i = 1; i < strs.length; i++) {
            String str = strs[i];
            for (int j = 0; j < length; j++) {
                if (str0.charAt(j) != str.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static String longestCommonPrefix2(String[] strs) {
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            String str = strs[i];
            prefix = getPrefix(prefix, str);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public static String getPrefix(String str1, String str2) {
        int index = 0;
        int min = Math.min(str1.length(), str2.length());
        for (int i = 0; i < min; i++) {
            if (str1.charAt(i) == str2.charAt(i)) {
                index++;
            }else {
                break;
            }
        }

        return str1.substring(0, index);
    }

    public static void main(String[] args) {
//        String[] strs = {"dog", "racecar", "car"};
        String[] strs = {"flower", "flow", "flight"};
        String prefix = longestCommonPrefix(strs);
        String prefix2 = longestCommonPrefix2(strs);
        System.out.println(prefix);
        System.out.println(prefix2);
    }
}
